/** @type {HTMLCanvasElement}*/ 
const canvas = document.getElementById('canvas1')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight

let mouse = {
    x:canvas.width/2,
    y:canvas.height/2
}

let colorArray = [
    '#97A7F8',
    '#C957CA',
    '#76E2FE'
]

let ClickDistance = 0

window.addEventListener('mousemove',function(event){
    mouse.x = event.clientX
    mouse.y = event.clientY
})
window.addEventListener('mousedown',function(){
    ClickDistance = 1
})
window.addEventListener('mouseup',function(){
    ClickDistance = -1
})
function randomIntFromRange(low,high){
    return Math.floor( Math.random() * ( high - low + 1 ) + low)
}

function randomDoubleFromRange(low,high){
    return Math.random() * ( high - low + 1 ) + low
}

function randomColors(colors){
    return colors[Math.floor(Math.random() * colors.length)]
}

function getDistance(x1,y1,x2,y2){
    let dx = x1-x2
    let dy = y1-y2
    return Math.sqrt( dx * dx + dy * dy)
}

class Particle{
    constructor(x,y,radius,color){
        this.x = x
        this.y = y
        this.radius = radius
        this.color = color
        this.theta = randomDoubleFromRange(0,Math.PI * 2)
        this.speed = 0.03
        this.dragSpeed = 0.04
        this.distance = randomIntFromRange(40,60)
        this.lastdistance = this.distance
        this.lastMouse = {
            x:x,
            y:y
        }
    }
    draw(lastPosition){
        ctx.beginPath()
        ctx.strokeStyle = this.color
        ctx.lineWidth = this.radius
        // ctx.arc(this.x,this.y,this.radius,0,Math.PI * 2)
        ctx.moveTo(lastPosition.x,lastPosition.y)
        ctx.lineTo(this.x,this.y)
        ctx.stroke()
    }
    update(){
        let lastPosition = {
            x:this.x,
            y:this.y
        }
        // 拖拽效果
        this.lastMouse.x += (mouse.x - this.lastMouse.x) * this.dragSpeed
        this.lastMouse.y += (mouse.y - this.lastMouse.y) * this.dragSpeed

        this.x = this.lastMouse.x + Math.cos(this.theta) * this.distance
        this.y = this.lastMouse.y + Math.sin(this.theta) * this.distance

        // this.x = mouse.x + Math.cos(this.theta) * this.distance
        // this.y = mouse.y + Math.sin(this.theta) * this.distance

        this.theta += this.speed
        if(this.distance < this.lastdistance){
            this.distance = this.lastdistance
        }
        this.distance += ClickDistance * Math.random() * 2
        this.draw(lastPosition)
    }
}


let p = new Particle(canvas.width/2,canvas.height/2,5,'red')
let particles = []
for(let i = 0; i < 30; i++){
    let color = randomColors(colorArray)
    particles.push(new Particle(canvas.width/2,canvas.height/2,3,color))
}
function animate(){
    // 轨迹效果
    ctx.fillStyle = 'rgba(255,255,255,0.1)'
    ctx.fillRect(0,0,canvas.width,canvas.height)
    particles.forEach((particle) => {
        particle.update()
    })
    requestAnimationFrame(animate)
}
animate()
